package com.cloud.pdd.config;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.cloud.pdd.model.domain.UserInfo;
import com.cloud.pdd.model.enums.CookieConst;
import com.cloud.pdd.model.response.AjaxResp;
import com.cloud.common.security.AES;
import com.cloud.common.util.CookieUtils;
import com.cloud.pdd.service.PddUsersService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Package: com.*.*.interceptor
 * @ClassName: AdminInterceptor
 * @Description:拦截器
 * @author: zk
 * @date: 2019年9月19日 下午2:20:57
 */
public class AdminInterceptor implements HandlerInterceptor {
    @Autowired
    PddUsersService pddUsersService;

    /**
     * 在请求处理之前进行调用（Controller方法调用之前）
     */
    @SneakyThrows
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
//        System.out.println("执行了TestInterceptor的preHandle方法");
        String requestURI = request.getRequestURI();
        String url = "/login";
        //        String url = request.getContextPath() + "/m/login";
        String cookie = CookieUtils.getCookie(request, CookieConst.loginPddCookie);
        if (StrUtil.isEmpty(cookie)) {
            if (requestURI.contains("ajax/center")) {
                //如果个人后台的ajax请求，要返回json格式登录提示
                AjaxResp ajaxResp = new AjaxResp();
                ajaxResp.setCode(301);
                ajaxResp.setMsg("请先登录");
                String s = JSONUtil.toJsonStr(ajaxResp);
                response.setCharacterEncoding("UTF-8");
                response.getWriter().write(s);
            } else {
                response.sendRedirect(url);
            }
            return false;
        }
        String s = AES.aesDecrypt(cookie);
        UserInfo userInfo = JSONUtil.toBean(s, UserInfo.class);
        if (null == userInfo) {
            response.sendRedirect(url);
        }
        return true;
        //如果设置为true时，请求将会继续执行后面的操作
    }

    /**
     * 请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
//         System.out.println("执行了TestInterceptor的postHandle方法");
    }

    /**
     * 在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行（主要是用于进行资源清理工作）
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
//        System.out.println("执行了TestInterceptor的afterCompletion方法");
    }

}